package com.xzl.authserver.controller;

import com.xzl.authserver.service.AuthService;
import com.xzl.boilerplate.common.controller.BaseController;
import com.xzl.boilerplate.common.dto.ResultResponse;
import com.xzl.boilerplate.common.dto.exception.BizCode;
import com.xzl.boilerplate.common.dto.exception.BizException;
import com.xzl.boilerplate.common.security.JwtAuthenticationRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.AuthenticationException;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

@RestController
public class AuthController extends BaseController{
    @Value("${jwt.header}")
    private String tokenHeader;

    @Autowired
    private AuthService authService;

    @RequestMapping(value = "/auth", method = RequestMethod.GET)
    public int createAuthenticationToken2(){
        return 1;
    }

    @RequestMapping(value = "/auth", method = RequestMethod.POST)
    public ResultResponse createAuthenticationToken(
            @RequestBody JwtAuthenticationRequest authenticationRequest) throws AuthenticationException{
        Map map;
        try {
            map = authService.login(authenticationRequest.getUsername(), authenticationRequest.getPassword());
        } catch (IOException e) {
            throw new BizException(BizCode.USER_AUTH_REQUEST);
        }

        // Return the token

        return ResultResponse.createSuccessResponse(map);
    }

    @RequestMapping(value = "/auth/refresh", method = RequestMethod.GET)
    public ResultResponse refreshAndGetAuthenticationToken(
            HttpServletRequest request) throws AuthenticationException{
        String token = request.getHeader(tokenHeader);
        String refreshedToken = authService.refresh(token);
        if(refreshedToken == null) {
            return ResultResponse.createFailureResponse(BizCode.TOKEN_UNPRESENT);
        } else {
            return ResultResponse.createSuccessResponse(refreshedToken);
        }
    }

//    @RequestMapping(value = "${jwt.route.authentication.register}", method = RequestMethod.POST)
//    public User register(@RequestBody User addedUser) throws AuthenticationException{
//        return authService.register(addedUser);
//    }
}
